package com.example.music_mediaplayer.control;

import com.example.music_mediaplayer.api.ILrcBuilder;
import com.example.music_mediaplayer.model.LrcRow;
import com.example.music_mediaplayer.tool.LogoutT;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by quan on 2018/1/18.
 * 解析歌词，得到LrcRow的集合
 */

public class DefaultLrcBuilder implements ILrcBuilder{
    public static final String TAG = "DefaultLrcBuilder";
    @Override
    public List<LrcRow> getLrcRows(String rawLrc) {
        LogoutT.logout("getLrcRows by rawString");
        if (rawLrc == null || rawLrc.length() == 0){
            LogoutT.logout("getLrcRows rawLrc null or empty");
            return null;
        }
        StringReader reader = new StringReader(rawLrc);
        BufferedReader br = new BufferedReader(reader);
        String line = null;
        List<LrcRow> rows = new ArrayList<>();
        try{
            //循环地读取歌词的每一行
            do{
                line = br.readLine();
                LogoutT.logout("lrc raw line:"+line);
                if (line != null && line.length() > 0){
//                    LogoutT.logout("11111111");
                    //解析每一行歌词，得到每行歌词的集合，因为有些歌词重复有多个时间，就可以解析出多个歌词行来
                    List<LrcRow> lrcRows = LrcRow.createRows(line);
                    if (lrcRows != null && lrcRows.size() > 0){
//                        LogoutT.logout("22222");
                        for (LrcRow row : lrcRows){
                            rows.add(row);
                        }
                    }
                }
            }while (line!=null);
            LogoutT.logout(rows.size()+"   rows.size   6666666666");
            if (rows.size()>0){
                //根据歌词行的时间排序
                Collections.sort(rows);
                if (rows!=null&&rows.size()>0){
                    for (LrcRow lrcRow : rows){
                        LogoutT.logout("lrcRow:"+lrcRow.toString());
                    }
                }
            }
        } catch (IOException e) {
            LogoutT.logout("parse exceptioned:"+e.getMessage());
            return null;
        }finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            reader.close();
        }
        return rows;
    }
}
